package com.live.proxy.sql;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDatabaseHelper extends SQLiteOpenHelper {
	//用户信息
	public static final String user_info = "create table user_info ("
			+ "id integer primary key autoincrement, "
			+ "nickname text DEFAULT '',"
			+ "account text DEFAULT '',"
			+ "password text DEFAULT '',"
			+ "status integer DEFAULT 1,"
			+ "token text DEFAULT '',"
			+ "inte_yue integer DEFAULT 0,"//积分余额
			+ "auto_type integer DEFAULT 1,"//授权类型 1代理 2贴牌
			+ "direct_type integer DEFAULT 0,"//直属类型 0不是直属 1直属
			+ "app_id text DEFAULT '',"//应用ID
			+ "app_name text DEFAULT ''"//应用名称
			+") ";

	public MyDatabaseHelper(Context context, String name, CursorFactory cursorfactory, int version,
                            DatabaseErrorHandler databaseerrorHandler) {
		super(context, name, cursorfactory, version, databaseerrorHandler);

	}
	@Override
	public void onCreate(SQLiteDatabase db) {
		//创建数据库时会调用，我们需要在里面创建我们的数据表。onCreate只会调用一次，如果数据库已经存在，那么打开数据库是不会回调onCreate的。
		db.execSQL(user_info);
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		//升级数据库时会调用，我们可以在这里面做升级操作
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
//		// onOpen在每次打开数据库时都会调用。
	}
	//检查某表是否存在
	public static boolean IsHaveTable(SQLiteDatabase db,String tablename){
		boolean isHave = false;
		Cursor cursor = db.rawQuery("select name from sqlite_master where type='table' ", null);
		while (cursor.moveToNext()) {
			// 遍历出表名
			if (cursor.getString(0).equals(tablename)) {
				isHave = true;
				break;
			}
		}
		cursor.close();
		return isHave;
	}
	/**
	 * 检查表中某列是否存在
	 */
	private boolean checkColumnExists2(SQLiteDatabase db, String tableName
			, String columnName) {
		boolean result = false ;
		Cursor cursor = null ;
		try{
			cursor = db.rawQuery( "select * from sqlite_master where name = ? and sql like ?"
					, new String[]{tableName , "%" + columnName + "%"} );
			result = null != cursor && cursor.moveToFirst() ;
		}catch (Exception e){
			Log.e("TAG","checkColumnExists2..." + e.getMessage()) ;
		}finally{
			if(null != cursor && !cursor.isClosed()){
				cursor.close() ;
			}
		}
		return result ;
	}
}
